<template>
  <div style="padding: 10px">
    <!--    功能区-->
    <div style="margin: 10px 0">
      <el-button type="primary" @click="add">新增</el-button>
      <el-button type="primary" @click="insert">导入</el-button>
      <br>
      <el-input v-model="numKey" clearable placeholder="根据课程代码检索" style="width: 20%;margin-top: 5px"/>
      <el-button style="margin: 5px" type="primary" @click="searchByNum">查询</el-button>
      <el-input v-model="nameKey" clearable placeholder="根据课程名称检索" style="width: 20%;margin-top: 5px"/>
      <el-button style="margin: 5px" type="primary" @click="searchByName">查询</el-button>
      <el-input v-model="teacherKey" clearable placeholder="根据授课教师检索" style="width: 20%;margin-top: 5px"/>
      <el-button style="margin: 5px" type="primary" @click="searchByTeacher">查询</el-button>
    </div>
    <el-table :data="tableData" border stripe style="width: 100%">
      <el-table-column fixed label="课程名" prop="courseName" sortable/>
      <el-table-column fixed label="课程编号" prop="courseNumber"/>
      <el-table-column label="开课院系" prop="schoolId"/>
      <el-table-column label="学时" prop="coursePeriod"/>
      <el-table-column label="学分" prop="courseCredit"/>
      <el-table-column label="任课教师" prop="workNumber"/>
      <el-table-column label="课程介绍" prop="courseDesc"/>
      <el-table-column label="选课容量" prop="courseCapacity"/>
      <el-table-column label="可选专业" prop="majorId"/>
      <el-table-column fixed="right" label="操作" width="250px">
        <template #default="scope">
          <el-button type="text" @click="handleEdit(scope.row)">修改课程信息</el-button>
          <el-button type="text" @click="$router.push({path:'/timePlace',query:{courseSerialNumber:scope.row.courseSerialNumber}})">修改时间信息</el-button>
          <el-popconfirm title="确定删除此信息？" @confirm="handleDelete(scope.row.number)">
            <template #reference>
              <el-button type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <div style="margin: 10px 0">

      <el-dialog v-model="dialogVisible" title="新增课程" width="40%">
        <el-form :model="form" :rules="rules" label-position="left" label-width="80px" style="padding-left: 50px" ref="form">
          <el-form-item label="课程名" prop="courseName">
            <el-input v-model="form.courseName" style="width: 50%"/>
          </el-form-item>
          <el-form-item label="课程编号" prop="courseNumber">
            <el-input v-model.number="form.courseNumber" style="width: 50%"/>
          </el-form-item>
          <el-form-item label="学时" prop="coursePeriod">
            <el-input v-model.number="form.coursePeriod" style="width: 50%"/>
          </el-form-item>
          <el-form-item label="学分" prop="courseCredit">
            <el-input v-model.number="form.courseCredit" style="width: 50%"/>
          </el-form-item>
          <el-form-item label="开课院系" prop="school">
            <el-select v-model="form.schoolName" filterable placeholder="请选择">
              <el-option
                  v-for="item in schoolList"
                  :key="item.schoolId"
                  :label="item.schoolName"
                  :value="item.schoolId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="任课教师" prop="teacher">
            <el-select v-model="this.form.selectedTeacher" filterable multiple placeholder="请选择">
              <el-option
                  v-for="item in teacherList"
                  :key="item.teacherId"
                  :label="item.teacherName+' '+item.teacherId"
                  :value="item.teacherId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="开课学年" prop="schoolYear">
            <el-select v-model="form.schoolYear" placeholder="请选择">
              <el-option
                  v-for="item in YearList" :key="item" :label="item" :value="item">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="开课学期" prop="semester">
            <el-radio v-model="this.form.semester" :label="1">第一学期</el-radio>
            <el-radio v-model="this.form.semester" :label="2">第二学期</el-radio>
          </el-form-item>
          <el-form-item label="课程介绍">
            <el-input v-model="form.courseDesc" style="width: 80%" type="textarea"/>
          </el-form-item>
          <el-form-item label="选课容量" prop="capacity">
            <el-input v-model.number="form.courseCapacity" style="width: 30%"/>
          </el-form-item>
          <el-form-item label="开放范围">
            <el-radio v-model="this.form.openToAll" :label="true">通选</el-radio>
            <el-radio v-model="this.form.openToAll" :label="false">非通选</el-radio>
          </el-form-item>
          <!--            如果不选择通选，则必须选择专业。-->
          <el-form-item v-if="this.form.openToAll===false" label="可选专业">
            <el-select v-model="this.form.majorGroup" filterable multiple placeholder="请选择">
              <el-option
                  v-for="item in majorList"
                  :key="item.majorId"
                  :label="item.majorName"
                  :value="item.majorId">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="saveForm">确 定</el-button>
          </span>
        </template>
      </el-dialog>
      <el-dialog v-model="insertBoxVisible" center title="导入" width="30%">
        <!--        TODO:这个地方的测试不太会弄，可能要等后端好了再测-->
        <el-upload
            :before-remove="beforeRemove"
            :file-list="fileList"
            :limit="1"
            :multiple="false"
            :on-error="handleError"
            :on-exceed="handleExceed"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            accept=".csv"
            action="http://localhost:8082/course/importCsv"
            class="upload"
        >
          <el-button slot="trigger" size="small" style="margin-left: 110px" type="primary">选取文件</el-button>
          <div slot="tip" class="el-upload__tip" style="margin-left: 110px">只支持csv文件的上传</div>
        </el-upload>

        <template #footer>
          <span class="dialog-footer">
            <el-button @click="insertBoxVisible = false">取 消</el-button>
            <el-button type="primary" @click="confirm">确 定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import request from "@/utils/request";

export default {
  name: "CourseInfo",
  components: {},
  data() {
    return {
      //导入课程
      insertBoxVisible: false,
      fileList: [],
      //显示表格
      tableData: [
        {courseName: '软件工程',
        courseSerialNumber:110,
        courseNumber:111}
      ],
      //选项初始化
      schoolList: [
        {
          schoolId: '1',
          schoolName: '黄金糕'
        }, {
          schoolId: '2',
          schoolName: '双皮奶'
        }, {
          schoolId: '3',
          schoolName: '蚵仔煎'
        }
      ],
      majorList: [
        {
          majorId: '1',
          majorName: '黄金糕'
        }, {
          majorId: '2',
          majorName: '双皮奶'
        }, {
          majorId: '3',
          majorName: '蚵仔煎'
        }, {
          majorId: '4',
          majorName: '龙须面'
        }, {
          majorId: '5',
          majorName: '北京烤鸭'
        }],
      teacherList: [
        {
          teacherId: 22008888,
          teacherName: '校长'
        },
        {
          teacherId: 22008881,
          teacherName: '小张'
        }
      ],
      //新增课程
      dialogVisible: false,
      form: {},
      tempTimeForm: {},
      YearList: [2022, 2023, 2024, 2025, 2026],
      //新增课程规则
      rules: {
        courseName: [{required: true, message: '请输入课程名', trigger: 'blur'},],
        courseNumber: [{required: true, message: '请输入课程编号', trigger: 'blur'},
          {type: 'number', message: '课程编号应为数字'}],
        coursePeriod: [{required: true, message: '请输入学时', trigger: 'blur'}, {type: 'number', message: '学时应为数字'}],
        courseCredit: [{required: true, message: '请输入学分', trigger: 'blur'}, {type: 'number', message: '学分应为数字'}],
        school: [{required: true, message: '请选择开课院系', trigger: 'blur'}],
        teacher: [{required: true, message: '请选择任课教师', trigger: 'blur'}],
        schoolYear: [{required: true, message: '请选择学年', trigger: 'blur'}],
        semester: [{required: true, message: '请选择学期', trigger: 'blur'}],
        capacity: [{required: true, message: '请填写选课容量', trigger: 'blur'}, {type: 'number', message: '选课容量应为数字'}]
      },
      //可选课程时间表格
      scheduleData: [
        {courseNo: '1', name: '软件工程'}
      ],
      numKey: '',
      nameKey: '',
      teacherKey: ''
    }
  },
  created() {
    this.load()
  },
  methods: {
    load() {
      request.get("http://124.70.179.188:8082/course/allCourseInfo").then(res => {
        this.tableData = res.data
        this.loadOptions();
      })

    },
    insert() {
      this.insertBoxVisible = true
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    handleError(response, file, fileList) {
      this.$message.error('上传失败')
    },
    handleSuccess(response, file, fileList) {
      this.$message.success('上传成功')
      this.load() // 刷新表格数据
    },
    handlePreview(file) {
      console.log(file);
    },
    beforeRemove(file) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    confirm() {
      this.insertBoxVisible = false // 关闭弹窗
    },
    //课程添加
    add() {
      this.dialogVisible = true
      this.form = {
        school: null,
        selectedTeacher: [],
        description: null,
        capacity: null,
        name: null,
        number: null,
        hour: null,
        credit: null,
        openToAll: true,
        schoolYear: 2022,
        semester: 1,
        majorGroup: [],
        timeAndPlaces: []
      }
    },
    loadOptions() {
      request.get("http://124.70.179.188:8082/major/majorList").then(res => {
        if (res.code === '0') {
          this.majorList = res.data.majorList
        }
      })
      request.get("http://124.70.179.188:8082/school/schoolList").then(res => {
        if (res.code === '0') {
          this.schoolList = res.data.schoolList
          console.log("schoolList:"+JSON.stringify(res))
        }
      })
      request.get("http://124.70.179.188:8082/tea/teaInfo").then(res => {
        if (res.code === '0') {
          this.teacherList = res.data
        }
      })
    },
    saveForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id) { //若id存在则更新数据（编辑），若id不存在则新增数据
            request.put("http://124.70.179.188:8082/course/add", this.form).then(res => {
              // 判断是否返回成功，若失败给出失败的信息
              if (res.code === '0') {
                this.$message({
                  type: "success",
                  message: "更新成功"
                })
              } else {
                this.$message({
                  type: "error",
                  message: res.message
                })
              }
              this.load() // 刷新表格数据
              this.dialogVisible = false // 关闭弹窗
            })
          } else {
            request.post("http://124.70.179.188:8082/course/add", this.form).then(res => {
              console.log(res)
              // 判断是否返回成功，若失败给出失败的信息
              if (res.code === '0') {
                this.$message({
                  type: "success",
                  message: "新增成功"
                })
              } else {
                this.$message({
                  type: "error",
                  message: res.message
                })
              }
              this.load() // 刷新表格数据
              this.dialogVisible = false // 关闭弹窗
            })
          }
        }
      })

    },
    //表格管理
    handleEdit(row) {
      this.form = JSON.parse(JSON.stringify(row))
      this.dialogVisible = true
    },
    handleDelete(number) {
      request.delete("http://124.70.179.188:8082/course/del" + number).then(res => {
        console.log(res)
        if (res.code === 0) {
          this.$message.success("删除成功")
          this.load()
        } else {
          this.$message.error("删除失败")
        }
      })
    },
    //搜索
    searchByNum() {
      request.get("http://124.70.179.188:8082/course/admin/findByCourseNum?cnum=" + this.numKey).then(res => {
            this.tableData = res.data
            this.total = res.data.length;
            this.loadOptions();
          }
      )
    },
    searchByName() {
      request.get("http://localhost:8082/course/admin/findByCourseName?cname=" + this.nameKey).then(res => {
            this.tableData = res.data
            this.total = res.data.length;
            this.loadOptions();
          }
      )
    },
    searchByTeacher() {
      request.get("http://124.70.179.188:8082/course/admin/findByTeaName?teaname=" + this.teacherKey).then(res => {
            this.tableData = res.data
            this.total = res.data.length;
            this.loadOptions();
          }
      )
    }
  }
}
</script>
csv
<style scoped>
</style>